/**
 * 
 */
package com.zhaoyan.cms.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;


import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.zhaoyan.cms.common.CmsResultMsg;
import com.zhaoyan.cms.constant.CmsConstant;
import com.zhaoyan.cms.pojo.Article;
import com.zhaoyan.cms.pojo.Category;
import com.zhaoyan.cms.pojo.Channel;
import com.zhaoyan.cms.pojo.Comment;
import com.zhaoyan.cms.pojo.User;
import com.zhaoyan.cms.pojo.Vote;
import com.zhaoyan.cms.pojo.vo.VoteVo;
import com.zhaoyan.cms.service.ArticleService;

/**
 * @author zhaoyan
 *
 * 2020年1月20日
 */
@Controller
@RequestMapping("article")
public class ArticleController {

	@Value("${upload.path}")
	private String uploadPath;
	
	@Autowired
	private ArticleService articleService; 
	
	
	/**
	 *	取得当前用户发布过，未删除的文章
	 * @param pageNum
	 * @param session
	 * @param m
	 * @return
	 */
	@RequestMapping("myArticles")
	public String findUserArticles(@RequestParam(defaultValue = "1")Integer pageNum ,HttpSession session ,Model m){
		
		User loginUser = (User) session.getAttribute(CmsConstant.USER_KEY);
		
		if(loginUser == null) {
			return "redirect:/user/login";
		}
		
		System.out.println(loginUser);
		
		PageInfo<Article> articlePage = articleService.findArticles(loginUser.getId(),pageNum);
		System.err.println(articlePage.getList().size());
		
		m.addAttribute("articlePage",articlePage );
		
		return "home/myArticles"; 
	}
	
	/**
	 * 去到添加页面
	 * @param m
	 * @return
	 */
	@RequestMapping("toAddArticle")
	public String toAddArticle(Model m) {
		
	    return 	"home/addArticle";
	}
	/**
	 * ajax请求频道列表
	 * @return
	 */
	@RequestMapping("findChannels")
	@ResponseBody
	public CmsResultMsg<List<Channel>> findChannels(){
		
		List<Channel> findChannels = articleService.findChannels();
		
		if(findChannels == null) {
			return new CmsResultMsg<List<Channel>>(1,CmsConstant.FAILED,null);
		}
		
		return  new CmsResultMsg<List<Channel>>(0,CmsConstant.SUCCEED,findChannels);
	}
	/**
	 * ajax请求类别 二级联动
	 * @param channelId
	 * @return
	 */
	@RequestMapping("findCategorys")
	@ResponseBody
	public CmsResultMsg<List<Category>> findCategorys(Integer channelId){
		
		List<Category> findCategoryList = articleService.findCategoryList(channelId);
		
		if(findCategoryList==null) {
			return new CmsResultMsg<List<Category>>(1,CmsConstant.FAILED,null);
		}
		
		return  new CmsResultMsg<List<Category>>(0,CmsConstant.SUCCEED,findCategoryList);
	}
	
	@RequestMapping("addArticle")
	@ResponseBody
	public CmsResultMsg<String> addArticle(HttpSession session ,
			Article article,
			MultipartFile imgFile){
		User user = (User) session.getAttribute(CmsConstant.USER_KEY);
		
		if(user == null) {
			
			return new CmsResultMsg<String>(20, CmsConstant.FAILED, "您尚未登录");
			
		}
		
		String imgPath = null;
		
		try {
			imgPath = upFile(imgFile);
			System.out.println(imgPath);
			
			//	设置文件的路径
			article.setPicture(imgPath);
			System.err.println(imgPath);
			
			//	设置发布的用户id
			article.setUser_id(user.getId());
			
			System.out.println(article);
			
			
			
			Integer num = articleService.addArticle(article);
			
			
			
			if(num > 0) {
				
				return new CmsResultMsg<String>(0,CmsConstant.SUCCEED,"发布成功"); 
			}
			
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			return new CmsResultMsg<String>(20,CmsConstant.FAILED,"处理异常");
		}
		
		
		return new CmsResultMsg<String>(10,CmsConstant.FAILED,"发布失败");
	}
	/**
	 * 删除文章
	 * @param id
	 * @return
	 */
	@RequestMapping("delOne")
	@ResponseBody
	public CmsResultMsg<String> delOne(Integer id) {
		
		Integer num = articleService.delOne(id);
		
		if(num > 0) {
			return new CmsResultMsg<String>(0, CmsConstant.SUCCEED, "删除失败");	
		}
		
		return new CmsResultMsg<String>(1, CmsConstant.FAILED, "删除失败");
	}
	
	/**
	 * 去修改的界面，在 后台查出文章的内容
	 * @param m
	 * @param id
	 * @return
	 */
	@RequestMapping("toUpdateOne")
	public String toUpdateOne(Model m,Integer id) {
		
		Article article = articleService.findArticle(id);
		
		System.err.println(article);
		
		m.addAttribute("article",article);
		
		return "home/update";
	}
	
	/**
	 * 修改文章
	 * @param session
	 * @param article
	 * @param imgFile
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public CmsResultMsg<String> update(HttpSession session ,
			Article article,
			MultipartFile imgFile){
		User user = (User) session.getAttribute(CmsConstant.USER_KEY);
		
		if(user == null) {
			
			return new CmsResultMsg<String>(20, CmsConstant.FAILED, "您尚未登录");
			
		}
		
		String imgPath = null;
		
		try {
			imgPath = upFile(imgFile);
			System.out.println(imgPath);
			
			//	设置文件的路径
			article.setPicture(imgPath);
			System.err.println(imgPath);
			
			//	设置发布的用户id
			article.setUser_id(user.getId());
			
			System.out.println(article);
			
			
			
			Integer num = articleService.updateOne(article);
			
			
			
			if(num > 0) {
				
				return new CmsResultMsg<String>(0,CmsConstant.SUCCEED,"修改成功"); 
			}
			
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			return new CmsResultMsg<String>(30,CmsConstant.FAILED,"处理异常");
		}
		
		
		return new CmsResultMsg<String>(10,CmsConstant.FAILED,"修改失败");
	}
	
	@RequestMapping("showDetails")
	public String showDetails(Integer id , Model m) {
		
		Article article = articleService.findArticle(id);
		
		m.addAttribute("article",article );
		
		return "details";
		
	}
	
	
	/**
	 * 	
	 * @param pageNum
	 * @param articeId
	 * @return
	 */
	@RequestMapping("showCommentList")
	private String showComments(Model m ,@RequestParam(defaultValue = "1")Integer pageNum,Integer articleId){
		
		PageInfo<Comment> commentPage = articleService.findComment(pageNum,articleId);
		
		System.out.println(articleId);
		
		m.addAttribute("commentPage", commentPage);
		
		return "comments";
	}
	/**
	 *  	评论文章
	 * @param session
	 * @param articleId
	 * @param content
	 * @return
	 */
	@RequestMapping("addComment")
	@ResponseBody
	private CmsResultMsg<String> addComment(HttpSession session,Integer articleId,String content ){
		
		Comment comment = new Comment();
		
		User user = (User) session.getAttribute(CmsConstant.USER_KEY);
		
		if(user == null) {
			return new CmsResultMsg<String>(5, CmsConstant.FAILED, "用户未登录！");
		}
		
		comment.setArticleId(articleId);
		
		comment.setContent(content);
		
		comment.setUserId(user.getId());
		
		Integer num = articleService.addComment(comment);
		
		if(num > 0) {
			
			return new CmsResultMsg<String>(0, CmsConstant.SUCCEED, "评论成功！");
		}
		
		return new CmsResultMsg<String>(6, CmsConstant.FAILED, "评论失败！");
	}
	
	
	/**
	 * 	去发布投票的界面
	 * @param vote
	 * @return
	 */
	@RequestMapping("toAddVote")
	public String toAddVote() {
		
		return "home/vote";
	}
	
	/**
	 * 	添加投票
	 * @param vote
	 * @param session
	 * @return
	 */
	@RequestMapping("addVote")
	@ResponseBody
	public CmsResultMsg<String> addVote(VoteVo voteVo,HttpSession session) {
		
		String json = toJson(voteVo);
		
		User user = (User) session.getAttribute(CmsConstant.USER_KEY);
		
		if(user == null) {
			
			return new CmsResultMsg<String>(5, CmsConstant.FAILED, "用户未登陆");
				
		}
		
		Vote vote = new Vote();
		
		vote.setContent(json);
		
		vote.setTitle(voteVo.getQuestion());
		
		Integer num = articleService.addVote(vote);
		
		if(num > 0) {
			
			return new CmsResultMsg<String>(0, CmsConstant.SUCCEED, "添加成功");
		}
		
		
		
		return new CmsResultMsg<String>(6, CmsConstant.FAILED, "添加失败");
	}

	
	/**
	 * 	把对象转换成json字符串
	 * @param obj
	 * @return
	 */
	private String	toJson(Object obj) {
		
		LinkedHashMap<Character,String> optionsMap = new LinkedHashMap<>();
		
		
		LinkedList<String> options = ((VoteVo) obj).getOptions();
		
		char node = 'A';
		
		for (String string : options) {
			
			optionsMap.put(node, string);
			
			node++;
			
		}
		return JSON.toJSONString(optionsMap);
	}
	
	
	/**
	 * 把文件写入指定的位置
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	private String upFile(MultipartFile file) throws IllegalStateException, IOException {
		// TODO Auto-generated method stub
		
		if(file==null || file.isEmpty())
			return "";
		
		//获取原来的文件名称
		String srcFileName = file.getOriginalFilename();
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		String todayStr  = dateFormat.format(new Date());
		
		File filePath = new File(uploadPath + "/" + todayStr);
		//如果路径不存在则创建路径
		if(!(filePath.exists())) {
			filePath.mkdirs();
		}
		//计算扩展名
		String suffixeName=srcFileName.substring(srcFileName.lastIndexOf('.'));
		//求新的文件名称
		String dstFileName=UUID.randomUUID().toString() +  suffixeName;
		
		file.transferTo(new File(filePath + "/" + dstFileName));
		
		return todayStr + "/" + dstFileName;
	}
		
}
